// index.js
import { getPhoneNumber, postWxLogin, getUserInfo, getWorkBenchData, getTaskList, setTaskFinish } from '../../api/index'
import { userType, findTypeByValue, frequencyType, taskCountType, classifyType } from '../../utils/type'

const app = getApp()
Page({
	data: {
		active: 0,
		logined: false,
		baseCls: 'page_account',
		tabActive: 0,
		finishIds: [],
		loginRadio: false,
		show: false,
		userInfo: '',
		myPatient: {
			Finish: 0,
			Focus: 0,
			onGoing: 0,
			Total: 0
		},
		opacity: 0,
		infoshow: false
  },
  onLoad: function(options){
    if(options.login){
      this.login()
    }
  },
	onShow: function(options) {
    console.log(options);
		this.getTabBar().init();
    let userInfo = wx.getStorageSync('userInfo');
		if (userInfo) {
			this.handleLoginAction(true, userInfo)
			this.workBenchData();
			this.updateUserinfo();
			this.Todaytask();
		}
  },
	finishMyTask(event) {
    let id = event.target.id
    const unfinishRows = this.data.unfinishRows
    const finishRows = this.data.finishRows
    const finishIds = this.data.finishIds
    const isComplete = finishIds.includes(id)

    let newFinishIds = []
    let newFinishRows = []
    let newUnfinishRows = []

    if(isComplete){
      const row = finishRows.find(item => item.id === id)
      newFinishIds = finishIds.filter(item => item !== id)
      newFinishRows = finishRows.filter(item => item.id !== id)
      newUnfinishRows = [
        ...unfinishRows,
        row
      ]
    }else{
      const row = unfinishRows.find(item => item.id === id)
      newFinishIds = [
        ...finishIds,
        id
      ]
      newFinishRows = [
        ...finishRows,
        row
      ]
      newUnfinishRows = unfinishRows.filter(item => item.id !== id)
    }

    this.setData({
      unfinishRows: newUnfinishRows,
      finishRows: newFinishRows,
      Todaytask: [...newUnfinishRows, ...newFinishRows]
    })
    
    setTimeout(() => {
      this.setData({
        finishIds: newFinishIds,
      })
    } , 200)

    // 提交变动
    this.Updatestate(id, !isComplete ? 1 : 0)
  },
  
  /**
   * 更新任务状态
   * */
  Updatestate(id, type) {
    setTaskFinish({
      id,
      isComplete: type
    })
  },

	loginRadio_onChange(event) {
		this.setData({
			loginRadio: event.detail,
		});
  },

	onClickHide() {
		this.setData({
			show: false
		});
  },
  
	Agreement() {
		wx.showToast({
			title: '请先同意用户协议',
			icon: 'none',
			duration: 2000
		})
  },

  /**
   * 获取用户信息
   * @param {*} mobile 
   * @param {*} code 
   */
  getInfo(){
    getUserInfo().then(res => {
      let userInfo = res.user;
      if(userInfo){
        console.log(userInfo);
        wx.setStorageSync('userInfo', userInfo);
        this.handleLoginAction(true, userInfo)
        this.onShow();
      }else{
        setTimeout(() => {
          this.setData({
            show: false
          })
        }, 5000)

        wx.showToast({
          title: '用户角色不存在，请联系管理人员',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 微信授权登录
   * @param {*} e 
   */
  wxLogin(mobile){
    const _self =  this;
    wx.login({
      success(res) {
        postWxLogin({
          code: res.code,
          mobile,
          terminal: 'admin'
        }).then(data => {
          if(data.code === 200){
            wx.setStorageSync('token', data.token)
            _self.getInfo();
          }else if(data.code === 401){
            _self.handleLoginAction(false)
          }
        })
      }
    })
  },

	/**
   * 获取手机号验证登陆
   * @param {*} e 
   */
	PhoneNumber(e) {
    const code = e.detail.code;
    if(code){
      getPhoneNumber({code}).then(res => {
        let mobile = res.mobile;
        this.wxLogin(mobile)
      })
    }
  },
  
	/**
	 * 更新用户信息
	 */
	 updateUserinfo(){
    getUserInfo().then(res => {
      let userInfo = res.user;
      if(userInfo){
        userInfo.type = findTypeByValue(userInfo.type, userType)
        wx.setStorageSync('userInfo', userInfo);
        this.handleLoginAction(true, userInfo)
      }
    })
	 },
   
	/**
   * 我的患者 管理中 onGoing / Finish / Total / Focus
	 * 重点关注 fldBYw2pvPRIO
   */
	workBenchData() {
		let that = this;
    getWorkBenchData().then(res => {
      const { finish, follow, progress, task, total } = res.data;

      that.setData({
        'myPatient.onGoing': progress,
        'myPatient.Finish': finish,
        'myPatient.Focus': follow,
        'myPatient.Total': total
      })
    }).catch(res => {
      if(res.code === 401){
        that.handleLoginAction(false)
      }
    })
  },
  
	/**
   * 今日任务
   */
	Todaytask() {
		let that = this;
		that.setData({
			finishIds: [],
			Todaytask: ''
		})
    const countType = findTypeByValue('today', taskCountType)
    const classify = classifyType[1]
    getTaskList({
      pageNum: 1,
      pageSize: 999,
      classify: classify?.value,
      type: countType?.value
    }).then(res => {
      const rows = res.rows;
      const unfinishRows = [];
      const finishRows = [];
      rows.forEach(item => {
        if(item.isComplete){
          finishRows.push(item)
        }else{
          unfinishRows.push(item)
        }
      })

      const data = {
        finishIds: finishRows.map(item => item.id),
        finishRows: finishRows,
        unfinishRows: unfinishRows,
        Todaytask: [...unfinishRows, ...finishRows]
      }

      this.setData(data)
    })
  },
  
	/**
   * 跳转任务列表
   */
	goTasklist() {
		wx.reLaunch({
			url: '/pages/task/index'
		})
  },
  
  /**
   * 协议
   * @param {*} e 
   */
   protocolHtml(e){
	   var url = e.currentTarget.dataset.url;
	   var title = e.currentTarget.dataset.title;
	   wx.navigateTo({
	   	url: '/pages/protocolShow/index?url=' + url + '&title =' + title
	   })
   },

  /**
  *  任务详情
  * */
  getTaskInfo(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    var infokey = e.currentTarget.dataset.key;
    let taskList = this.data.Todaytask
    let currTask = taskList.filter(item => item.id === id)
    if(currTask.length > 0){
      currTask = currTask[0]
    }
    let userLabel = findTypeByValue(currTask.executorUserType, userType)?.label || '-'
    let executor = `${userLabel}：${currTask.executorUserName}`
    let frequency = findTypeByValue(currTask.frequency, frequencyType)?.label || '-'

    that.setData({
      infoshow: true,
      infokey: infokey,
      TaskInfo: {
        ...currTask,
        executor,
        frequency
      },
      edit_recordId: id,
      sms_checked: true
    })
    
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  /**
   *  添加任务弹窗取消
   */
  hideshow() {
    this.setData({
      infoshow: false,
      sms_checked: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
  },

  onChange() {

  },
  noop() {

  },

  handleLoginAction(logined, userInfo){
    if(logined){
      this.setData({
        userInfo: userInfo,
        logined: true,
        show: false
      })
    }
  },

  login(){
    this.setData({
      show: true,
      logined: false
    })
  }
})